package com.example.demo.service.impl;

import com.example.demo.dao.BooksMapper;
import com.example.demo.dao.LendMapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.pojo.*;
import com.example.demo.service.LendService;
import com.example.demo.utils.Result;
import com.example.demo.utils.ResultFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 借阅Service
 */
@Service
public class LendServiceImpl implements LendService {

    @Autowired
    private LendMapper lendMapper;
    @Autowired
    private BooksMapper booksMapper;
    @Autowired
    private UserMapper userMapper;

    private Logger logger = LoggerFactory.getLogger(LendServiceImpl.class);

    @Override
    public Result reservationBookByBookId(int book_id, int reader_id) {


        Books books = this.booksMapper.selBooksAndStockByBookId(book_id);
        logger.info(" " + books);
        if(books.getIs_deletestate() == 0){ //该图书已出库
            return  ResultFactory.failureWithStatus(999,"该图书已出库");
        }else if(books.getBook_state() == 3){
            return  ResultFactory.failureWithStatus(999,"该图书不可预约");
        }else{
            if(books.getBook_count() >0) { //有库存
                //预约状态 1 - 不超时、2 - 超时、3-已被借走
                //插入预约表
                Reservation reservation = new Reservation(book_id, reader_id, new Date(), 1);
                int i = this.lendMapper.insertReservation(reservation);
                if(i>0){
                    books.setIs_deletestate(0); //设置图书出库
                    books.setBook_state(2);
                    this.booksMapper.updateBookIsdeletestateByBookId(books);
                    this.booksMapper.updateBookStateByBookId(books);
                    //插入出库表  1-借出,2-出库，3-预约，4-归还,5-入库
                    OutBound outBound = new OutBound(book_id,1,new Date(),3);
                    this.booksMapper.insertOutBound(outBound);
                    return  ResultFactory.successWithStatus(200,"图书预约成功，请在2天内来将书借走，超时借阅失效");
                }else{
                    return ResultFactory.failureWithStatus(999,"图书预约出现异常，预约失败");
                }

            }else{
                //无库存
                return  ResultFactory.failureWithStatus(999,"该图书没有库存了");
            }

        }
    }

    /**
     * 图书借阅是否超时
     */

    private  void reservationTimeIsTimeOut() {
        List<Reservation> reservations = this.lendMapper.selAllReservation();
        for (Reservation reservation:reservations){
//            logger.info("LendServiceImpl :" + this.lendMapper.reservationTimeToNowDayNum(reservation.getReservation_date()));
            //预约状态 1 - 不超时、2 - 超时、3-已被借走
            if(reservation.getReservatiion_state() == 3 || reservation.getReservatiion_state() == 2){ //图书已被借走
                continue;
            }else {
                int i = this.lendMapper.reservationTimeToNowDayNum(reservation.getReservation_date());
                //logger.info("reservationTimeIsTimeOut ： " +i);
                if (i >= 48) { //超时未被借走
                    //1-未超时 2-超时 3-已被借走
                    this.lendMapper.setReservationState(2,reservation.getBook_id(),reservation.getReader_id());
                    //图书状态改为is_deletestate = 1  预约未被借走 图书入库
                    Books books = this.booksMapper.selBooksByBookId(reservation.getBook_id());
                    books.setIs_deletestate(1);
                    books.setBook_state(1);
                    this.booksMapper.updateBookIsdeletestateByBookId(books);
                    this.booksMapper.updateBookStateByBookId(books);
                    //预约状态设置为 超时状态
                    this.lendMapper.setReservationState(2,reservation.getBook_id(),reservation.getReader_id());
                }
            }
        }

    }

    /**
     * 在当前时间基础上加上指定天数得到新日期
     * @return
     */
    private Date addDate(Date date,long day){
        long time = date.getTime(); //得到指定日期的毫秒数
        day  = day * 24 * 60 *60 * 1000; //要加上的天数转成毫秒数
        time += day;
        return new Date(time);           //将毫秒数转换为时间格式

    }

    //计算需要交纳的罚金，并更新数据库
    public void computedFine(){
        List<Lend> lends = this.lendMapper.selLendList();
        for (Lend lend: lends) {
            logger.info("sssss：" + lend.getIs_return());
            if(lend.getIs_return() == 1 || lend.getFine() == 1){
                continue;
            }else{
                int i = this.lendMapper.selLendListBackDateToNowDayNum(lend.getSer_num(), lend.getBack_date());
                if(i>0){
                    //逾期，需要交罚金，0.1元/天
                    // 罚款 1-已交,0-未交 2-未欠款
                    //1-归还,0-未归还
                    this.lendMapper.updateLendListFinenumAndFineBySerNum(lend.getSer_num(),new BigDecimal(i*0.1),0);
                }
            }

        }


    }

    //出库
    @Override
    public Result lendBookByBookId(int book_id, int reader_id) {
        User userByReaderId = this.userMapper.findUserByReaderId(reader_id);
        if(userByReaderId.getState() == 2){
            return ResultFactory.failureWithStatus(999,"借阅卡被暂停了，暂时无法借书，请到管理员处查看原因");
        }

        //1.刷新库存表信息
        reservationTimeIsTimeOut();
        //2.判断预约表是否存在记录
        Reservation reservation = new Reservation();
        reservation.setBook_id(book_id);
        reservation.setReader_id(reader_id);
        Reservation reservation1 = this.lendMapper.selReservation(reservation);
        if(reservation1 == null || reservation1.getReservatiion_state() == 2){
            logger.info("lendBookByBookId：" + 1);
            //3.没有预约记录
            Books books = this.booksMapper.selBooksByBookId(book_id);
            if(books.getBook_state() == 3 || books.getIs_deletestate() == 0){

                return  ResultFactory.failureWithStatus(999,books.getName() +"图书借阅失败 ");
            }
            Lend lend= new Lend(book_id,reader_id,new Date(),addDate(new Date(),60),new BigDecimal(0),0,2);
            int i = this.lendMapper.insertLendList(lend);
            if(i>0){
                //库存量-1;  插入出库表; 借出次数 + 1;

                books.setIs_deletestate(0);
                books.setBook_state(2);
                this.booksMapper.updateBookIsdeletestateByBookId(books);
                this.booksMapper.updateBookStateByBookId(books);

                //图书借出状态 1-借出,2-出库，3-预约，4-归还,5-入库
                OutBound outBound = new OutBound(book_id,1,new Date(),1);

                this.booksMapper.insertOutBound(outBound);
                this.booksMapper.updateBookLendTimesByBookId(book_id);


                return  ResultFactory.successWithStatus(200,"图书借阅成功");
            }else{
                return  ResultFactory.failureWithStatus(999,"图书借阅失败");
            }

        }else{
            logger.info("lendBookByBookId：" + 3);
            //4.不超时
            Lend lend = new Lend(book_id,reader_id,new Date(),addDate(new Date(),60),new BigDecimal(0),0,2);
            int i = this.lendMapper.insertLendList(lend);
            if(i>0){
                //插入成功
                this.lendMapper.setReservationState(3,book_id,reader_id);
                //图书借出状态 1-借出,2-出库，3-预约，4-归还,5-入库
                OutBound outBound = new OutBound(book_id,1,new Date(),1);
                this.booksMapper.insertOutBound(outBound);
                this.booksMapper.updateBookLendTimesByBookId(book_id);
                return  ResultFactory.successWithStatus(200,"图书借阅成功");
            }else{

                return  ResultFactory.failureWithStatus(999,"图书借阅失败");
            }

        }

    }

    //入库
    @Override
    public Result returnBookByBookId(int ser_num, int reader_id) {


        //lend_list
        Lend lend = new Lend();
        //(1)修改back_time为当前时间
        lend.setSer_num(ser_num);
        lend.setBack_date(new Date());
        //(2)解决状态改为归还状态is_return=1
        lend.setIs_return(1);
        this.lendMapper.updateLendListBackTimeAndIsreturnbySerNum(lend);
        //outBound 入库表
        //(1) book_id, 1,new Date(), 4-归还

        Lend lend1 = this.lendMapper.selLendListBySerNum(ser_num,reader_id);
        OutBound outBound = new OutBound(lend1.getBook_id(),1,new Date(),4);
        this.booksMapper.insertOutBound(outBound);
        //book 修改图书状态
        //book.setIs_deletestate = 1；book.book_state = 1
        Books books = this.booksMapper.selBooksByBookId(lend1.getBook_id());
        books.setBook_state(1);
        books.setIs_deletestate(1);
        this.booksMapper.updateBookIsdeletestateByBookId(books);
        this.booksMapper.updateBookStateByBookId(books);

        return ResultFactory.successWithStatus(200,"图书归还成功！！！");

    }

    @Override
    public PageBean<Lend> queryLendList(int currentPage,int pageSize) {
        computedFine(); //先刷新 查看是否逾期欠费

        int colNums = this.lendMapper.selLendListCount();//记录总数
        PageHelper.startPage(currentPage,pageSize);
        List<Lend> lends = this.lendMapper.selAllLendList();
        PageInfo<Lend> lendPageInfo = new PageInfo<>(lends);
        List<Lend> list = lendPageInfo.getList();
        PageBean<Lend> pageData=new PageBean<>(currentPage,pageSize,colNums);
        pageData.setItem(list);
        return pageData;
    }

    @Override
    public PageBean<Lend> queryLendListByList(int currentPage, int pageSize, int reader_id) {
        computedFine(); //先刷新 查看是否逾期欠费
        int colNums = this.lendMapper.selLendListCountByReaderId(reader_id);//记录总数
        PageHelper.startPage(currentPage,pageSize);
        List<Lend> lends = this.lendMapper.selAllReaderLendList(reader_id);
        PageInfo<Lend> lendPageInfo = new PageInfo<>(lends);
        List<Lend> list = lendPageInfo.getList();
        PageBean<Lend> pageData=new PageBean<>(currentPage,pageSize,colNums);
        pageData.setItem(list);
        return pageData;
    }

    @Override
    public Result payFine(int ser_num) {
        this.lendMapper.updateLendListFineBySerNum(ser_num,1);
        return ResultFactory.successWithData(200,"缴费成功");
    }

    @Override
    public PageBean<Lend> fineHistory(int currentPage, int pageSize) {
       int colnums = this.lendMapper.selFineHistoryCount();
        if(colnums == 0 ){
            return null;
        }
        PageHelper.startPage(currentPage,pageSize);
        List<Lend> lends = this.lendMapper.selFineHistory();
        PageInfo<Lend> lendPageInfo = new PageInfo<>(lends);
        List<Lend> list = lendPageInfo.getList();
        PageBean<Lend> pageData=new PageBean<>(currentPage,pageSize,colnums);
        pageData.setItem(list);
        return pageData;
    }

    @Override
    public Result renewBookBySerNum(int ser_num,int reader_id) {
        Lend lend = this.lendMapper.selLendListBySerNum(ser_num,reader_id);
        this.lendMapper.renewBookBySerNum(ser_num,addDate(lend.getBack_date(),30));
        return ResultFactory.successWithData(200,"图书续借成功");
    }

    @Override
    public Result queryLendListByQueryCriteria(int currentPage, int pageSize, QueryCriteria queryCriteria) {

        int i = this.lendMapper.selLendListCountByConditions(queryCriteria);
        if(i==0){
            return ResultFactory.failureWithStatus(999,"没有此图书");
        }
        PageHelper.startPage(currentPage,pageSize);
        List<Lend> lends = this.lendMapper.selLendListByConditions(queryCriteria);
        PageInfo<Lend> lendPageInfo = new PageInfo<>(lends);
        List<Lend> list = lendPageInfo.getList();
        PageBean<Lend> pageData = new PageBean<>(currentPage,pageSize,i);
        pageData.setItem(list);
        return ResultFactory.successWithStatusAndData(200,"查找成功",pageData);
    }

    @Override
    public Result queryReservationList(int currentPage, int pageSize) {
        int i = this.lendMapper.selAllReservationCount();
        if(i==0){
            return ResultFactory.failureWithStatus(999,"没有相关借阅记录");
        }
        PageHelper.startPage(currentPage,pageSize);
        List<Reservation> reservations = this.lendMapper.selAllReservation();
        PageInfo<Reservation> reservationPageInfo = new PageInfo<>(reservations);
        PageBean<Reservation> pageData = new PageBean<>(currentPage,pageSize,i);
        pageData.setItem(reservationPageInfo.getList());
        return ResultFactory.successWithStatusAndData(200,"查询成功",pageData);
    }
}
